package com.eastfair.auth.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.annotation.base.SubjectTypeEnum;
import com.eastfair.annotation.database.mybatis.auth.DataScope;
import com.eastfair.auth.company.LoginHandler;
import com.eastfair.auth.dao.BusinessMapper;
import com.eastfair.auth.dao.UserAccountMapper;
import com.eastfair.auth.dto.*;
import com.eastfair.auth.entity.*;
import com.eastfair.auth.enumeration.OrganizationOrgTypeEnum;
import com.eastfair.auth.enumeration.OrganizationVestTypeEnum;
import com.eastfair.auth.enumeration.UserAccountStatusEnum;
import com.eastfair.auth.exceptioncode.AuthServiceExceptionCode;
import com.eastfair.auth.service.*;
import com.eastfair.auth.vo.*;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperCacheServiceImpl;
import com.eastfair.core.encrypt.RSAEncrypt;
import com.eastfair.core.exception.BizException;
import com.eastfair.core.exception.NoBackBizException;
import com.eastfair.core.exception.code.ExceptionCode;
import com.eastfair.database.mybatis.typehandler.M9EncryptHandler;
import com.eastfair.database.mybatis.typehandler.TypeHandlerUtil;
import com.eastfair.model.DataIsolationVo;
import com.eastfair.point.business.auth.BusinLoadUserPermissPoint;
import com.eastfair.cache.auth.AccountUserCacheKeyBuilder;
import com.eastfair.cache.repository.CacheOps;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.businmodel.DBNameType;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.model.CacheKeyBuilder;

import com.eastfair.core.utils.Base64Util;
import com.eastfair.core.utils.MD5Util;
import com.eastfair.handler.EfTokenHandler;
import com.eastfair.jwt.model.AuthInfo;
import com.eastfair.jwt.model.JwtUserInfo;
import com.eastfair.jwt.service.JwtService;
import com.eastfair.log.point.PointUtil;
import com.eastfair.projectcore.api.ProjectCoreServiceFeign;
import com.eastfair.projectcore.dto.DataIsolationDTO;
import com.eastfair.projectcore.entity.Dictionary;
import com.eastfair.projectcore.entity.ProjectDb;
import com.eastfair.projectcore.enumeration.DataIsolationSystemSceneEnum;
import com.eastfair.projectcore.vo.MenuVO;
import com.eastfair.uid.baidu.rule.SnowFlakeRole;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.apache.commons.collections4.CollectionUtils;;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.eastfair.core.base.R.SUCCESS_CODE;
import static com.eastfair.core.exception.code.ExceptionCode.*;

/**
 * <p>
 * 业务实现类
 * 用户账户信息
 * </p>
 *
 * @author ligang
 * @date 2021-07-13
 */
@Slf4j
@Service
//@DS("#thread.tenant")
//@DS("#header.tenant")
//@DS("ds-2")
public class UserAccountServiceImpl extends SuperCacheServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    ProjectCoreServiceFeign projectCoreServiceFeign;

    @Autowired
    protected CacheOps cacheOps;

    @Autowired
    OrganizationService organizationService;

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    RoleService roleService;

    @Autowired
    UserOrganizationService userOrganizationService;
    @Autowired
    ResourceOrganizationService resourceOrganizationService;
    @Autowired
    JwtService jwtService;

    @Autowired
    EfTokenHandler efTokenHandler;

    @Autowired
    PointUtil pointUtil;

    @Autowired
    BusinessMapper businessMapper;

    @Autowired
    LoginHandler loginHandler;
    @Autowired
    SnowFlakeRole snowFlakeRole;
    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerSave(UserAccount model) {
        model.setId(snowFlakeRole.findUidSimple());
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        if (StringUtils.isBlank(model.getName())) {
            //空，随机给登录名
            String name = nonredundantUser();
            model.setName(name);
            model.setPwdOutTime(LocalDateTime.now().plusDays(90));
        }
        return R.successDef();
    }

    /**
     * 获取不重复的10位数字
     *
     * @return
     */
    public String nonredundantUser() {
        String name = "";
        for (int n = 0; n < 10; n++) {
            name += (int) (10 * (Math.random()));
        }
        //是否重复
        int num = queryCodeSize(name);
        if (num > 0) {
            nonredundantUser();
        }
        return name;
    }

    public int queryCodeSize(String name) {
        QueryWrapper<UserAccount> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.lambda().eq(UserAccount::getName, name);
        }
        queryWrapper.lambda().eq(UserAccount::getIsDeleted, BusinessConstant.DELETE_NO);
        return count(queryWrapper);
    }

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<UserAccount> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }

    @Override
    public CacheKeyBuilder getCacheKeyBuilder() {
        return new AccountUserCacheKeyBuilder();
    }

    @Override
    public UserAccount getUser(UserAccount userAccount) {
        List<UserAccount> userAccountList = listOfUserAccount(userAccount, null);
        if (userAccountList != null && !userAccountList.isEmpty()) {
            return userAccountList.get(0);
        }
        return null;
    }

    @Override
    public R<UserAccountVo> register(UserAccountDto userAccountDto) {
        //登录名不能重复
        if (ContextUtil.getProjectId() == null) {
            //项目id不能为空
            return R.fail(PROJECT_ID_ERROR);
        }
        //查询用户是否存在
        List<UserAccount> userAccountList = queryUserOfregister(userAccountDto);
        if (userAccountList != null && !userAccountList.isEmpty()) {
            if (StringUtils.isNotBlank(userAccountDto.getName()) && userAccountDto.getName().equals(userAccountList.get(0).getName())) {
                return R.fail(LOGINNAME_AGAIN);
            } else if (StringUtils.isNotBlank(userAccountDto.getEmail()) && userAccountDto.getEmail().equals(userAccountList.get(0).getEmail())) {
                return R.fail(EMIAL_AGAIN);
            } else if (StringUtils.isNotBlank(userAccountDto.getMobile()) && userAccountDto.getMobile().equals(userAccountList.get(0).getMobile())) {
                return R.fail(MOBILE_AGAIN);
            }
            return R.fail(LOGINNAME_AGAIN);
        }
        UserAccount saveUserAccount = BeanUtil.toBean(userAccountDto, getEntityClass());
        saveUserAccount.setStatus(UserAccountStatusEnum.NORMAL);
//        saveUserAccount.setPassword(StringUtils.isNotBlank(saveUserAccount.getPassword()) ? getStorePassword(saveUserAccount.getPassword()) : null);
//        saveUserAccount.setPassword(getStorePassword(StringUtils.isNotBlank(saveUserAccount.getPassword()) ? saveUserAccount.getPassword() : BusinessConstant.initPassword));
        saveUserAccount.setPassword(StringUtils.isNotBlank(saveUserAccount.getPassword()) ? saveUserAccount.getPassword() : BusinessConstant.initPassword);
        //默认游客
        saveUserAccount.setIsTourist(BusinessConstant.YES);
        saveUserAccount.setIsP(BusinessConstant.YES);
        //手机号默认是登录名
        saveUserAccount.setName(userAccountDto.getMobile());
        //组装团队id
        assembleTeam(saveUserAccount);
        save(saveUserAccount);
        //用户加入到子系统
        addSubSystemUser(saveUserAccount.getId());
        UserAccountVo userAccountVo = doToVo(saveUserAccount);
        //加载token信息
        loadToken(userAccountVo, userAccountDto);
        //添加到组织里
        if (userAccountDto.getOrgIds() != null && !userAccountDto.getOrgIds().isEmpty()) {
            for (Long orgId : userAccountDto.getOrgIds()) {
                organizationService.addUseridOfOrg(orgId, Arrays.asList(userAccountVo.getId()), userAccountDto.getIsLeader());
            }
        }
        //添加用户角色
        if (userAccountDto.getRoleIds() != null && !userAccountDto.getRoleIds().isEmpty()) {
            userRoleService.addUserRole(Arrays.asList(saveUserAccount.getId()), userAccountDto.getRoleIds());
        }

        return R.success(userAccountVo);
    }

    @Override
    public List<UserAccount> queryUserOfregister(UserAccountDto userAccountDto) {
        //查询用户是否存在
        log.info("queryUserOfregister:查询用户是否存在");
        QueryWrapper<UserAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserAccount::getIsDeleted, BusinessConstant.DELETE_NO);
        log.info("queryUserOfregister:useraccountDto,email:{},mobile:{},name:{}");
        if (userAccountDto != null) {
            if (StringUtils.isBlank(userAccountDto.getEmail())
                    && StringUtils.isBlank(userAccountDto.getMobile())
                    && StringUtils.isBlank(userAccountDto.getName())){
                log.error("queryUserOfregister:参数都为空，无法获取用户是否存在，请给出用户的基本信息");
                return new ArrayList<>();
            }
            queryWrapper.and(wrapper -> {
                if (StringUtils.isNotBlank(userAccountDto.getEmail())) {
                    wrapper.eq("email", userAccountDto.getEmail().trim());
                    wrapper.or();
                }
                if (StringUtils.isNotBlank(userAccountDto.getMobile())) {
//                    wrapper.eq("mobile", userAccountDto.getMobile().trim());
                    wrapper.eq("mobile", TypeHandlerUtil.crypt(userAccountDto.getMobile().trim()));
                    wrapper.or();
                }
                if (StringUtils.isNotBlank(userAccountDto.getName())) {
                    wrapper.eq("name", userAccountDto.getName().trim());
                }
            });
        }
        List<UserAccount> userAccountList = list(queryWrapper);
        if (CollectionUtil.isNotEmpty(userAccountList)) {
            for (UserAccount userAccount : userAccountList) {
                userAccount.setMobile(TypeHandlerUtil.decrypt(userAccount.getMobile()));
            }
        }
        //查询用户
        return userAccountList;
    }

    @Override
    public R addSubSystemUser(Long userId) {
        UserAccount userAccount = getByIdCache(userId);
        //组装用户所在系统信息
        assembleSubSystem(userAccount, BusinessConstant.YES);
        //组装团队id
        assembleTeam(userAccount);
        updateById(userAccount);
        //加载token信息
        UserAccountVo userAccountVo = doToVo(userAccount);
        loadToken(userAccountVo, null);
        return R.success(userAccountVo);
    }

    @Override
    public R removeSubSystemUser(Long userId) {
        UserAccount userAccount = getByIdCache(userId);
        //组装用户所在系统信息
        assembleSubSystem(userAccount, BusinessConstant.NO);
        updateById(userAccount);
        return R.success();
    }

    /**
     * 组装用户所在系统信息
     *
     * @param userAccount
     * @return
     */
    @Override
    public UserAccount assembleSubSystem(UserAccount userAccount, int isAdd) {
        DataIsolationDTO dataIsolationDTO = new DataIsolationDTO();
        dataIsolationDTO.setId(ContextUtil.getSubSystemId());
        R<List<DataIsolationVo>> listR = projectCoreServiceFeign.queryDataIsolaction(dataIsolationDTO);
        if (SUCCESS_CODE == listR.getCode()) {
            List<DataIsolationVo> dataIsolationVoList = listR.getData();
            if (dataIsolationVoList != null && !dataIsolationVoList.isEmpty()) {
                DataIsolationVo dataIsolationVo = dataIsolationVoList.get(0);
                if (OrganizationOrgTypeEnum.P.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsP(isAdd);
                } else if (OrganizationOrgTypeEnum.P_VENUE.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPVenue(isAdd);
                } else if (OrganizationOrgTypeEnum.P_CERTIFICATE.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPCertificate(isAdd);
                } else if (OrganizationOrgTypeEnum.P_COMPOSITE_VENUE.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPCompositeVenue(isAdd);
                } else if (OrganizationOrgTypeEnum.P_COMPOSITE_COURT.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPCompositeCourt(isAdd);
                } else if (OrganizationOrgTypeEnum.P_COMPOSITE_PRODUCER.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPCompositeProducer(isAdd);
                } else if (OrganizationOrgTypeEnum.P_COMPOSITE_TRANSPORT.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPCompositeTransport(isAdd);
                } else if (OrganizationOrgTypeEnum.P_COMPOSITE_TRADE.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPCompositeTrade(isAdd);
                } else if (OrganizationOrgTypeEnum.P_COMPOSITE_MATING.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPCompositeMating(isAdd);
                } else if (OrganizationOrgTypeEnum.P_PAY.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPPay(isAdd);
                } else if (OrganizationOrgTypeEnum.P_EXHIBITOR_SELF.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPExhibitorSelf(isAdd);
                } else if (OrganizationOrgTypeEnum.P_CATERINGAPP.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPCateringapp(isAdd);
                } else if (OrganizationOrgTypeEnum.P_CATERING.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPCatering(isAdd);
                } else if (OrganizationOrgTypeEnum.P_PORTAL_OUT_VENUE.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPPortalOutVenue(isAdd);
                } else if (OrganizationOrgTypeEnum.P_PORTAL_OUT_OPERATION.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPPortalOutOperation(isAdd);
                } else if (OrganizationOrgTypeEnum.P_PORTAL_IN_WORK.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPPortalInWork(isAdd);
                } else if (OrganizationOrgTypeEnum.P_PORTAL_IN_WORKAPP.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPPortalInWorkapp(isAdd);
                } else if (OrganizationOrgTypeEnum.P_OPERATION_CENTER.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPOperationCenter(isAdd);
                } else if (OrganizationOrgTypeEnum.P_VISITOR_FRONT.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPVisitorFront(isAdd);
                } else if (OrganizationOrgTypeEnum.P_VISITOR_BACK.getCode().equals(dataIsolationVo.getSystemScene())) {
                    userAccount.setIsPVisitorBack(isAdd);
                }
            }
        }

        return userAccount;
    }


    /**
     * 组装用户所在系统信息
     *
     * @param userAccount
     * @return
     */
    @Override
    public UserAccount assembleTeam(UserAccount userAccount) {
        Long teamId = ContextUtil.getTeamId();
        if (teamId != null) {
            if (DataIsolationSystemSceneEnum.P_COMPOSITE_MATING == DataIsolationSystemSceneEnum.get(ContextUtil.getSystemScene())) {
                //综合-配套商管理 :: 配套商ID
                userAccount.setMatingId(teamId);
            } else if (DataIsolationSystemSceneEnum.P_COMPOSITE_TRANSPORT == DataIsolationSystemSceneEnum.get(ContextUtil.getSystemScene())) {
                //综合-主运管理 ::主运ID
                userAccount.setTransportId(teamId);
            } else if (DataIsolationSystemSceneEnum.P_COMPOSITE_PRODUCER == DataIsolationSystemSceneEnum.get(ContextUtil.getSystemScene())) {
                //综合-主运管理 ::搭建商ID
                userAccount.setProducerId(teamId);
            } else if (DataIsolationSystemSceneEnum.P_COMPOSITE_COURT == DataIsolationSystemSceneEnum.get(ContextUtil.getSystemScene())) {
                //综合-主场管理 ::主场ID
                userAccount.setCourtId(teamId);
            }
        }
        return userAccount;
    }


    /**
     * 获取团队id
     *
     * @param userAccount
     * @return
     */
    @Override
    public Long queryTeamId(UserAccount userAccount) {
        Long teamId = null;
        if (DataIsolationSystemSceneEnum.P_COMPOSITE_MATING == DataIsolationSystemSceneEnum.get(ContextUtil.getSystemScene())) {
            //综合-配套商管理 :: 配套商ID
            teamId = userAccount.getMatingId();
        } else if (DataIsolationSystemSceneEnum.P_COMPOSITE_TRANSPORT == DataIsolationSystemSceneEnum.get(ContextUtil.getSystemScene())) {
            //综合-主运管理 ::主运ID
            teamId = userAccount.getTransportId();
        } else if (DataIsolationSystemSceneEnum.P_COMPOSITE_PRODUCER == DataIsolationSystemSceneEnum.get(ContextUtil.getSystemScene())) {
            //综合-主运管理 ::搭建商ID
            teamId = userAccount.getProducerId();
        } else if (DataIsolationSystemSceneEnum.P_COMPOSITE_COURT == DataIsolationSystemSceneEnum.get(ContextUtil.getSystemScene())) {
            //综合-主场管理 ::主场ID
            teamId = userAccount.getCourtId();
        }
        return teamId;
    }

    /**
     * 用户是否在所在系统
     *
     * @param userAccount
     * @return
     */
    @Override
    public Integer isSubSystem(UserAccount userAccount) {
        if (OrganizationOrgTypeEnum.P.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsP();
        } else if (OrganizationOrgTypeEnum.P_VENUE.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPVenue();
        } else if (OrganizationOrgTypeEnum.P_CERTIFICATE.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPCertificate();
        } else if (OrganizationOrgTypeEnum.P_COMPOSITE_VENUE.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPCompositeVenue();
        } else if (OrganizationOrgTypeEnum.P_COMPOSITE_COURT.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPCompositeCourt();
        } else if (OrganizationOrgTypeEnum.P_COMPOSITE_PRODUCER.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPCompositeProducer();
        } else if (OrganizationOrgTypeEnum.P_COMPOSITE_TRANSPORT.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPCompositeTransport();
        } else if (OrganizationOrgTypeEnum.P_COMPOSITE_TRADE.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPCompositeTrade();
        } else if (OrganizationOrgTypeEnum.P_COMPOSITE_MATING.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPCompositeMating();
        } else if (OrganizationOrgTypeEnum.P_PAY.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPPay();
        } else if (OrganizationOrgTypeEnum.P_EXHIBITOR_SELF.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPExhibitorSelf();
        } else if (OrganizationOrgTypeEnum.P_CATERINGAPP.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPCateringapp();
        } else if (OrganizationOrgTypeEnum.P_CATERING.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPCatering();
        } else if (OrganizationOrgTypeEnum.P_PORTAL_OUT_VENUE.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPPortalOutVenue();
        } else if (OrganizationOrgTypeEnum.P_PORTAL_OUT_OPERATION.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPPortalOutOperation();
        } else if (OrganizationOrgTypeEnum.P_PORTAL_IN_WORK.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPPortalInWork();
        } else if (OrganizationOrgTypeEnum.P_PORTAL_IN_WORKAPP.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPPortalInWorkapp();
        } else if (OrganizationOrgTypeEnum.P_OPERATION_CENTER.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPOperationCenter();
        } else if (OrganizationOrgTypeEnum.P_VISITOR_FRONT.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPVisitorFront();
        } else if (OrganizationOrgTypeEnum.P_VISITOR_BACK.getCode().equals(ContextUtil.getSystemScene())) {
            return userAccount.getIsPVisitorBack();
        }
        return null;
    }

    @Override
    public Integer updUserEnable(Long userId) {
        UserAccount userAccount = getByIdCache(userId);
        if (userAccount != null) {
            userAccount.setIsEnabled(BusinessConstant.NO);
            updateById(userAccount);
        }
        return null;
    }


    @Override
    public HuaWeiAccountDTO sycnAcctionOfCreate(HuaWeiAccountDTO huaWeiAccountDTO) {
        // TODO: 2023/1/9 校验机构是否存在， 不存在则不能创建账号
        if (StringUtils.isBlank(huaWeiAccountDTO.getOrgId())) {
            return null;
        }
        Organization organization2 = new Organization();
        organization2.setHuaweiOrgId(huaWeiAccountDTO.getOrgId());
        List<Organization> organizationList2 = organizationService.listOfOrganization(organization2, null);
        if (CollectionUtil.isEmpty(organizationList2)) {
            return null;
        }

        String loginName = huaWeiAccountDTO.getLoginName();
        UserAccountDto userAccountDto2 = new UserAccountDto();
        userAccountDto2.setName(loginName);
        userAccountDto2.setRealName(huaWeiAccountDTO.getFullName());
        List<UserAccount> userAccountList = getUserByNameAllDb(userAccountDto2);
        if (userAccountList != null && !userAccountList.isEmpty()) {
            //存在，则更新系统
            UserAccount userAccount = userAccountList.get(0);
            userAccount.setMobile(huaWeiAccountDTO.getMobile());
            userAccount.setRealName(huaWeiAccountDTO.getFullName());
            //组装用户所在系统信息
            assembleSubSystem(userAccount, BusinessConstant.YES);
            updateById(userAccount);
            huaWeiAccountDTO.setUid(userAccount.getId() + "");
        } else {
            //新增
            UserAccount saveUserAccount = new UserAccount();
            saveUserAccount.setStatus(UserAccountStatusEnum.NORMAL);
//            saveUserAccount.setPassword(getStorePassword(StringUtils.isNotBlank(saveUserAccount.getPassword()) ? saveUserAccount.getPassword() : BusinessConstant.initPassword));
            saveUserAccount.setPassword(StringUtils.isNotBlank(saveUserAccount.getPassword()) ? saveUserAccount.getPassword() : BusinessConstant.initPassword);

            //默认游客
            saveUserAccount.setIsTourist(BusinessConstant.YES);
            saveUserAccount.setIsP(BusinessConstant.YES);
            //登录名
            saveUserAccount.setName(huaWeiAccountDTO.getLoginName());
            saveUserAccount.setMobile(huaWeiAccountDTO.getMobile());
            saveUserAccount.setRealName(huaWeiAccountDTO.getFullName());
            //组装用户所在系统信息
            assembleSubSystem(saveUserAccount, BusinessConstant.YES);
            save(saveUserAccount);
            huaWeiAccountDTO.setUid(saveUserAccount.getId() + "");
        }
        if (StringUtils.isNotBlank(huaWeiAccountDTO.getOrgId())) {
            Organization organization = new Organization();
            organization.setHuaweiOrgId(huaWeiAccountDTO.getOrgId());
            List<Organization> organizationList = organizationService.listOfOrganization(organization, null);
            if (CollectionUtil.isNotEmpty(organizationList)) {
                userOrganizationService.addUserOfOrg(organizationList.get(0).getId(),
                        Arrays.asList(Long.parseLong(huaWeiAccountDTO.getUid())), null);
            }
        }

        //添加角色
        if (CollectionUtil.isNotEmpty(huaWeiAccountDTO.getRoleId())) {
            List<Long> roleIds = new ArrayList<>();
            for (String id : huaWeiAccountDTO.getRoleId()) {
                roleIds.add(Long.parseLong(id));
            }
            List<Role> roleList = roleService.list(null, null, roleIds);
            if (CollectionUtil.isNotEmpty(roleList)) {
                //重新绑定
                userRoleService.addUserRole(Arrays.asList(Long.parseLong(huaWeiAccountDTO.getUid())),
                        roleList.stream().map(Role::getId).collect(Collectors.toList()));
            }
        }


        //默认给这个用户管理员所在的组织
//        Organization organization = new Organization();
//        organization.setParentId(BusinessConstant.parentId);
//        organization.setOrgType(OrganizationOrgTypeEnum.get(ContextUtil.getSystemScene()));
//        List<Organization> parentOrgList = organizationService.listOfOrganization(organization, null);
//        if (CollectionUtil.isNotEmpty(parentOrgList)) {
//            log.info("parentOrgList is {} ", JSONObject.toJSONString(parentOrgList));
//            userOrganizationService.addUserOfOrg(parentOrgList.get(0).getId(), Arrays.asList(Long.parseLong(huaWeiAccountDTO.getUid())));
//        }
        return huaWeiAccountDTO;
    }

    @Override
    public HuaWeiAccountDTO sycnAcctionOfUpd(HuaWeiAccountDTO huaWeiAccountDTO) {
        log.info("sycnAcctionOfUpd 根据华为推送的用户id，查询数据库中的该用户");
        UserAccount userAccount = getByIdCache(Long.parseLong(huaWeiAccountDTO.getUid()));
        userAccount.setRealName(huaWeiAccountDTO.getFullName());
        userAccount.setMobile(huaWeiAccountDTO.getMobile());
        if (huaWeiAccountDTO.getStatus() != null) {
            // TODO: 2023/1/4 只是没有这个系统权限
            log.info("sycnAcctionOfUpd 设置用户状态");
            if (huaWeiAccountDTO.getStatus() == 0) {
                userAccount.setIsEnabled(BusinessConstant.YES);
//                assembleSubSystem(userAccount, BusinessConstant.YES);
            } else if (huaWeiAccountDTO.getStatus() == 1) {
                userAccount.setIsEnabled(BusinessConstant.NO);
//                assembleSubSystem(userAccount, BusinessConstant.NO);
            }
        }
        log.info("sycnAcctionOfUpd 更新用户信息");
        updateById(userAccount);

        if (StringUtils.isNotBlank(huaWeiAccountDTO.getOrgId())) {
            //删除之前的所属机构
            log.info("sycnAcctionOfUpd 删除之前的所属机构");
            List<UserOrganization> userOrganizationList = userOrganizationService.listOfUserOrganization(null, Arrays.asList(userAccount.getId()), null);
            if (CollectionUtil.isNotEmpty(userOrganizationList)) {
                for (UserOrganization userOrganization : userOrganizationList) {
                    Organization organization = organizationService.getByIdCache(userOrganization.getOrganizationId());
                    if (organization != null && !BusinessConstant.parentId.equals(organization.getParentId())) {
                        userOrganizationService.removeUserOfOrg(userOrganization.getOrganizationId(),
                                Arrays.asList(userAccount.getId()));
                    }
                }
            }
            log.info("sycnAcctionOfUpd 存储华为传输的新机构");
            Organization organization = new Organization();
            organization.setHuaweiOrgId(huaWeiAccountDTO.getOrgId());
            List<Organization> organizationList = organizationService.listOfOrganization(organization, null);
            if (CollectionUtil.isNotEmpty(organizationList)) {
                userOrganizationService.addUserOfOrg(organizationList.get(0).getId(),
                        Arrays.asList(userAccount.getId()), null);
            }
        }

        log.info("sycnAcctionOfUpd 添加角色");
        //添加角色
        if (CollectionUtil.isNotEmpty(huaWeiAccountDTO.getRoleId())) {
            List<Long> roleIds = new ArrayList<>();
            for (String id : huaWeiAccountDTO.getRoleId()) {
                roleIds.add(Long.parseLong(id));
            }
            List<Role> roleList = roleService.list(null, null, roleIds);
            if (CollectionUtil.isNotEmpty(roleList)) {
                userRoleService.addUserRole(Arrays.asList(Long.parseLong(huaWeiAccountDTO.getUid())),
                        roleList.stream().map(Role::getId).collect(Collectors.toList()));
            }
        }

        return huaWeiAccountDTO;
    }

    @Override
    public HuaWeiAccountDTO sycnAcctionOfDel(HuaWeiAccountDTO huaWeiAccountDTO) {
        UserAccount userAccount = getByIdCache(Long.parseLong(huaWeiAccountDTO.getUid()));
        // TODO: 2023/1/4 只是没有这个系统权限
        assembleSubSystem(userAccount, BusinessConstant.NO);
//        userAccount.setIsEnabled(BusinessConstant.NO);
//        userAccount.setIsDeleted(BusinessConstant.YES);
        updateById(userAccount);
        return huaWeiAccountDTO;
    }


    @Override
    public R<UserAccountVo> registerOfCompany(UserAccountDto userAccountDto) {
        //登录名不能重复
        if (ContextUtil.getProjectId() == null) {
            //项目id不能为空
            return R.fail(PROJECT_ID_ERROR);
        }
        //查询用户是否存在
        QueryWrapper<UserAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserAccount::getIsDeleted, BusinessConstant.DELETE_NO);
        if (userAccountDto != null) {
            queryWrapper.and(wrapper -> {
                if (StringUtils.isNotBlank(userAccountDto.getEmail())) {
                    wrapper.eq("email", userAccountDto.getEmail());
                    wrapper.or();
                }
                if (StringUtils.isNotBlank(userAccountDto.getMobile())) {
                    wrapper.eq("mobile", TypeHandlerUtil.crypt(userAccountDto.getMobile()));
                }
            });
        }
        //查询用户
        List<UserAccount> userAccountList = list(queryWrapper);
        if (userAccountList != null && !userAccountList.isEmpty()) {
            return R.fail(LOGINNAME_AGAIN);
        }
        UserAccount saveUserAccount = BeanUtil.toBean(userAccountDto, getEntityClass());
        saveUserAccount.setStatus(UserAccountStatusEnum.NORMAL);
        saveUserAccount.setPassword(StringUtils.isNotBlank(saveUserAccount.getPassword()) ? saveUserAccount.getPassword() : null);
        //默认游客
        saveUserAccount.setIsTourist(BusinessConstant.YES);
        saveUserAccount.setCompanyId(userAccountDto.getCompanyId());
        saveUserAccount.setIsEmployee(BusinessConstant.YES);
        save(saveUserAccount);
        UserAccountVo userAccountVo = doToVo(saveUserAccount);
        //公司拉入员工
        return R.success(userAccountVo);
    }

    @Override
    @InterceptorIgnore(tenantLine = "true")
    public R<UserAccountVo> login(UserAccountDto userAccountDto) {
        UserAccount queryUserAccount = new UserAccount();
        BeanUtils.copyProperties(userAccountDto, queryUserAccount);
        //查询用户
        UserAccount resultUserAccount = getUser(queryUserAccount);
        if (resultUserAccount != null) {
            if (BusinessConstant.NO == resultUserAccount.getIsEnabled()) {
                throw BizException.wrap(ExceptionCode.USER_NO_ENABLED);
            }
            if (UserAccountStatusEnum.NORMAL.eq(resultUserAccount.getStatus())) {
                if (!isValidPassword(userAccountDto.getPassword(), resultUserAccount.getPassword())) {
                    //登陆失败操作
                    loginHandler.executeLoginFail(resultUserAccount.getId());
                    //密码错误
//                    return R.fail(JWT_USER_INVALID);
                    throw BizException.wrap(ExceptionCode.JWT_USER_INVALID);
                }
                //判断用户密码是否过期
                if (resultUserAccount.getPwdOutTime() != null && resultUserAccount.getPwdOutTime().isBefore(LocalDateTime.now())) {
                    throw BizException.wrap(ExceptionCode.JWT_USER_INVALID);
                }
                //登陆成功操作
                loginHandler.executeLoginSucc(resultUserAccount.getId());
                return R.success(assemblyUserAccount(resultUserAccount, userAccountDto));

            } else if (UserAccountStatusEnum.DELETE.eq(resultUserAccount.getStatus())) {
                //用户不存在
//                return R.fail(USER_NO_ERROR);
                throw BizException.wrap(ExceptionCode.USER_NO_ERROR);
            }
        }
        throw BizException.wrap(ExceptionCode.USER_NO_ERROR);
//        return R.fail(USER_NO_ERROR);
    }

    @Override
    public R<UserAccountVo> loginOfMobile(UserAccountDto userAccountDto) {
        UserAccount queryUserAccount = new UserAccount();
        queryUserAccount.setMobile(userAccountDto.getMobile());
        //查询用户
        UserAccount resultUserAccount = getUser(queryUserAccount);
        if (resultUserAccount != null) {
            if (UserAccountStatusEnum.NORMAL.eq(resultUserAccount.getStatus())) {
                return R.success(assemblyUserAccount(resultUserAccount, userAccountDto));
            } else if (UserAccountStatusEnum.DELETE.eq(resultUserAccount.getStatus())) {
                //用户不存在
                return R.fail(USER_NO_ERROR);
            }
        }
        return R.fail(USER_NO_ERROR);
    }

    @Override
    public R<UserAccountVo> loginOfEmail(UserAccountDto userAccountDto) {
        UserAccount queryUserAccount = new UserAccount();
        queryUserAccount.setEmail(userAccountDto.getEmail());
        //查询用户
        UserAccount resultUserAccount = getUser(queryUserAccount);
        if (resultUserAccount != null) {
            if (UserAccountStatusEnum.NORMAL.eq(resultUserAccount.getStatus())) {
                return R.success(assemblyUserAccount(resultUserAccount, userAccountDto));
            } else if (UserAccountStatusEnum.DELETE.eq(resultUserAccount.getStatus())) {
                //用户不存在
                return R.fail(USER_NO_ERROR);
            }
        }
        return R.fail(USER_NO_ERROR);
    }

    @Override
    public UserAccountVo assemblyUserAccount(UserAccount resultUserAccount, UserAccountDto userAccountDto) {
        if (resultUserAccount != null) {
            //用户是否在所在系统
            if (BusinessConstant.YES != isSubSystem(resultUserAccount)) {
                throw BizException.wrap(AuthServiceExceptionCode.USER_NO_SYSTEM);
            }
            UserAccountVo userAccountVo = doToVo(resultUserAccount);
//            //加载用户角色信息
//            loadUserRole(userAccountVo);
            //加载业务事件
            loadBusiness(userAccountVo);
            //加载token信息
            loadToken(userAccountVo, userAccountDto);

            //更新最新token
            efTokenHandler.addToken(userAccountVo.getAuthInfo().getToken(), ContextUtil.getTerminalType(), userAccountVo.getId());
            //添加到事件监听队列
//            BusinLoadUserPermissPoint businLoadUserPermissPoint = new BusinLoadUserPermissPoint();
//            businLoadUserPermissPoint.setUserIdList(Arrays.asList(resultUserAccount.getId()));
//            pointUtil.addBusinPointMsg(businLoadUserPermissPoint);


//            pointUtil.addTransactionPointMsg("记录日志");
            return userAccountVo;
        }
        return null;
    }

    @Override
    public R loginOut(Long userId) {
        return R.success();
    }


    /**
     * 加载用户角色信息
     *
     * @param userAccountVo
     */
    @Override
    public void loadUserRole(UserAccountVo userAccountVo) {
        //加载用户组织信息
        List<UserAccountVo> userAccountVoList = assembleUserOrg(Arrays.asList(userAccountVo));
        userAccountVo = userAccountVoList.get(0);
        //组装系统场景组织
        List<RoleVo> roleVoList = findRoleOfUserId(userAccountVo.getId());
        if (CollectionUtil.isNotEmpty(roleVoList)) {
            //角色去重
            Map<Long, List<RoleVo>> group2 = roleVoList.stream().collect(Collectors.groupingBy(RoleVo::getId));
            List<RoleVo> roleVoList2 = new ArrayList<>();
            for (List<RoleVo> roleVoList1 : group2.values()) {
                roleVoList2.add(roleVoList1.get(0));
            }
            roleVoList = roleVoList2;
            userAccountVo.setRoleVoList(roleVoList);
            userAccountVo.setRoleIds(roleVoList.stream().map(RoleVo::getId).collect(Collectors.toList()));
            List<MenuVO> menuVOList = organizationService.loadMenuNoButton(roleVoList);
            userAccountVo.setMenuVOList(menuVOList);
            Map<String, List<String>> resultMap = organizationService.loadMenuPermission(userAccountVo.getId(), roleVoList);
            userAccountVo.setPermissionList(resultMap.get("premission"));
        }


    }


    /**
     * 查询用户角色信息
     *
     * @param userId
     */
    @Override
    public List<RoleVo> findRoleOfUserId(Long userId) {
        //组装系统场景组织
        List<Long> orgIds = querySysteOrgIdsOfUserid(userId);
        List<RoleVo> roleVoList = new ArrayList<>();
        if (orgIds != null && !orgIds.isEmpty()) {
            roleVoList = organizationService.loadRole(orgIds);
        }
        //加载用户角色
        List<UserRole> userRoleList = userRoleService.findOfUser(Arrays.asList(userId));
        if (userRoleList != null && !userRoleList.isEmpty()) {
            List<RoleVo> roleVoList1 = roleService.findAllById(userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList()));
            if (roleVoList1 != null && !roleVoList1.isEmpty()) {
                if (roleVoList == null || roleVoList.isEmpty()) {
                    roleVoList = new ArrayList<>();
                }
                roleVoList.addAll(roleVoList1);
            }
        }
        return roleVoList;
    }

    @Override
    public List<OrganizationVo> findOrgOfUserId(Long userId) {
        List<Long> orgIds = querySysteOrgIdsOfUserid(userId);
        if (!CollectionUtils.isEmpty(orgIds)) {
            return organizationService.doToVos(organizationService.listOfOrganization(null, orgIds));
        }
        return new ArrayList<>();
    }

    //通过用户和系统场景，拿到系统orgid
    @Override
    public List<Long> querySysteOrgIdsOfUserid(Long userId) {
        //用户关联的组织
        UserOrganization userOrganization = new UserOrganization();
        userOrganization.setUserId(userId);
        List<UserOrganization> userOrganizationList = userOrganizationService.listOfUserOrganization(userOrganization, null, null);
        if (userOrganizationList == null || userOrganizationList.isEmpty()) {
            return null;
        }
        //系统场景
        OrganizationOrgTypeEnum organizationOrgTypeEnum = OrganizationOrgTypeEnum.get(ContextUtil.getSystemScene());
        Organization sysOrganization = organizationService.queryOrgOfType(organizationOrgTypeEnum, null);
        List<Long> orgIds = userOrganizationList.stream().map(UserOrganization::getOrganizationId).collect(Collectors.toList());
        List<Organization> organizationList = organizationService.listOfOrganization(null, orgIds);
        if (organizationList == null || organizationList.isEmpty()) {
            return null;
        }
        //过滤出父级组织的节点
        organizationList = organizationList.stream().filter(s -> {
            return s.getCode().indexOf(sysOrganization.getCode()) > -1;
        }).collect(Collectors.toList());
        if (organizationList == null || organizationList.isEmpty()) {
            return null;
        }
        return organizationList.stream().map(Organization::getId).collect(Collectors.toList());

    }

    @Override
    public void loadToken(UserAccountVo userAccountVo, UserAccountDto userAccountDto) {
        Long l = System.currentTimeMillis();

        JwtUserInfo jwtUserInfo = new JwtUserInfo();
        jwtUserInfo.setProjectId(userAccountVo.getProjectId());
        jwtUserInfo.setSubsystemId(ContextUtil.getSubSystemId());
//        if (userAccountVo.getSubsystemId() == null) {
//            jwtUserInfo.setSubsystemId(ContextUtil.getSubSystemId());
//        } else {
//            jwtUserInfo.setSubsystemId(userAccountVo.getSubsystemId());
//        }
        if (ContextUtil.getTeamId() != null) {
            jwtUserInfo.setTeamId(ContextUtil.getTeamId());
        }
        jwtUserInfo.setUserId(userAccountVo.getId());
        jwtUserInfo.setName(userAccountVo.getName());
        //系统场景
        jwtUserInfo.setSystemScene(ContextUtil.getSystemScene());
        jwtUserInfo.setRealName(userAccountVo.getRealName());
        jwtUserInfo.setIsAdmin(userAccountVo.getIsAdmin());
//        jwtUserInfo.setIsSuperAdmin(userAccountVo.getIsSuperAdmin());
        jwtUserInfo.setIsSuperAdmin(assembleIsSuperAdminOfSystemScene(userAccountVo));
        AuthInfo authInfo = jwtService.build(jwtUserInfo);
        userAccountVo.setAuthInfo(authInfo);
        log.info("token 耗时：{}", (System.currentTimeMillis() - l));
    }

    /**
     * 登陆者是否能看到所有数据
     *
     * @return
     */
    public Integer assembleIsSuperAdminOfSystemScene(UserAccountVo userAccountVo) {
//        if (DataIsolationSystemSceneEnum.P_CERTIFICATE == DataIsolationSystemSceneEnum.get(ContextUtil.getSystemScene())) {
//            //证件管理系统 ：直接登录制证系统的账号，说明能看到所有制证数据
//            return 1;
//        }
        return userAccountVo.getIsSuperAdmin();
    }

    /**
     * 组装租户ID
     *
     * @return
     */
    public void assembleTenantIdOfSystemScene(UserAccountVo userAccountVo) {
        if (DataIsolationSystemSceneEnum.P_COMPOSITE_MATING == DataIsolationSystemSceneEnum.get(ContextUtil.getSystemScene())) {
            //综合-配套商管理 :: 配套商ID
            ContextUtil.setTeamId(userAccountVo.getMatingId());
        } else if (DataIsolationSystemSceneEnum.P_COMPOSITE_TRANSPORT == DataIsolationSystemSceneEnum.get(ContextUtil.getSystemScene())) {
            //综合-主运管理 ::主运ID
            ContextUtil.setTeamId(userAccountVo.getTransportId());
        } else if (DataIsolationSystemSceneEnum.P_COMPOSITE_PRODUCER == DataIsolationSystemSceneEnum.get(ContextUtil.getSystemScene())) {
            //综合-主运管理 ::搭建商ID
            ContextUtil.setTeamId(userAccountVo.getProducerId());
        } else if (DataIsolationSystemSceneEnum.P_COMPOSITE_COURT == DataIsolationSystemSceneEnum.get(ContextUtil.getSystemScene())) {
            //综合-主场管理 ::主场ID
            ContextUtil.setTeamId(userAccountVo.getCourtId());
        }
    }


    /**
     * 加载业务事件
     *
     * @param userAccountVo
     */
    public void loadBusiness(UserAccountVo userAccountVo) {
        // TODO: 2021/7/28 业务事件在这添加
        assembleTenantIdOfSystemScene(userAccountVo);
//        if(userAccountVo.getSubsystemId()==null){
        userAccountVo.setSubsystemId(ContextUtil.getSubSystemId());
//        }
        log.info("teamid is {}", ContextUtil.getTeamId());
        ContextUtil.setUserId(userAccountVo.getId());
        ContextUtil.setName(userAccountVo.getName());
        //密码是否临近过期  <20天
        if (userAccountVo.getPwdOutTime() != null && userAccountVo.getPwdOutTime().isBefore(LocalDateTime.now().plusDays(20))) {
            userAccountVo.setIsNearOutTime(BusinessConstant.YES);
        } else {
            userAccountVo.setIsNearOutTime(BusinessConstant.NO);
        }
    }

//    public String getStorePassword(String password) {
//        return new String(Base64Util.base64Encrypt(MD5Util.getMD5String(password)));
//    }

    @Override
    public boolean isValidPassword(String password, String storePassword) {
//        String basePassword = new String(Base64Util.base64Encrypt(MD5Util.getMD5String(password)));
        return password.equals(storePassword);
    }

    @Override
    public List<UserAccount> getUserByNameAllDb(UserAccountDto userAccountDto) {
        DBNameType[] dbNameTypes = DBNameType.values();
        for (DBNameType dbNameType : dbNameTypes) {
            ContextUtil.setTenant(dbNameType.getDbName());
            UserAccount userAccount = new UserAccount();
            BeanUtils.copyProperties(userAccountDto, userAccount);
            if (StringUtils.isNotBlank(userAccount.getMobile())) {
                userAccount.setMobile(TypeHandlerUtil.crypt(userAccount.getMobile()));
            }
            List<UserAccount> userAccountList = businessMapper.listUserName(userAccount);
            //手动解密
            assemblePrivateKey(userAccountList);
//            List<UserAccount> userAccountList = listOfUserAccount(userAccount, null);
            if (userAccountList != null && !userAccountList.isEmpty()) {
                return userAccountList;
            }
        }
        return null;
    }

    @Override
    public List<UserAccount> listOfPhoneOrEmail(UserAccountDto userAccountDto) {
        //查询用户是否存在
        QueryWrapper<UserAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserAccount::getIsDeleted, BusinessConstant.DELETE_NO);
        if (userAccountDto != null) {
            queryWrapper.and(wrapper -> {
                if (StringUtils.isNotBlank(userAccountDto.getEmail())) {
                    wrapper.eq("email", userAccountDto.getEmail());
                    wrapper.or();
                }
                if (StringUtils.isNotBlank(userAccountDto.getMobile())) {
                    wrapper.eq("mobile", TypeHandlerUtil.crypt(userAccountDto.getMobile()));
                }
            });
        }
        //查询用户
        List<UserAccount> userAccountList = list(queryWrapper);
        return userAccountList;
    }

    @Override
    public IPage<UserAccountVo> pageVo(PageParams<UserAccountDto> params) {
        UserAccountDto userAccountDto = params.getModel();
        QueryWrapper<UserAccountDto> queryWrapper = new QueryWrapper<>();
        userAccountDto.setSubsystemId(ContextUtil.getSubSystemId());
        queryWrapper.eq(StringUtils.isNotBlank(userAccountDto.getEmail()), "u.email", userAccountDto.getEmail())
                .like(StringUtils.isNotBlank(userAccountDto.getName()), "u.name", userAccountDto.getName())
                .like(StringUtils.isNotBlank(userAccountDto.getNickName()), "u.nick_name", userAccountDto.getNickName())
                .eq(StringUtils.isNotBlank(userAccountDto.getMobile()), "u.mobile", TypeHandlerUtil.crypt(userAccountDto.getMobile()))
                .eq(userAccountDto.getIsEnabled() != null, "u.is_enabled", userAccountDto.getIsEnabled())
                .eq(userAccountDto.getIsDeleted() != null, "u.is_deleted", userAccountDto.getIsDeleted());
        //组装费劲的系统查询语句
        assembleQueryWrapper(queryWrapper);
        StringBuilder stringBuilder = new StringBuilder();
        if (userAccountDto.getOrgIds() != null && !userAccountDto.getOrgIds().isEmpty()) {
            stringBuilder.append(" and o.organization_id in (");
            stringBuilder.append(StringUtils.join(userAccountDto.getOrgIds(), ","));
            stringBuilder.append(")");
            queryWrapper.apply("u.id in ( select user_id from c_user_organization o where o.is_deleted =0" + stringBuilder.toString() + ")");
        }
        Page<UserAccountDto> servePage = new Page<>(params.getCurrent(), params.getSize());
        IPage<UserAccountVo> userAccountVoIPage = businessMapper.queryUser(servePage, queryWrapper);
        //加载用户组织信息
        assembleUserOrg(userAccountVoIPage.getRecords());

        //手动解密
        assembleVoPrivateKey(userAccountVoIPage.getRecords());

        //加载用户组织信息
        assembleUserDataVo(userAccountVoIPage.getRecords());

        return userAccountVoIPage;
    }

    /**
     * 组装费劲的系统查询语句
     *
     * @param queryWrapper
     */
    public void assembleQueryWrapper(QueryWrapper<UserAccountDto> queryWrapper) {
        queryWrapper.eq(OrganizationOrgTypeEnum.P.getCode().equals(ContextUtil.getSystemScene()), "u.is_p", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_VENUE.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_venue", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_CERTIFICATE.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_certificate", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_COMPOSITE_VENUE.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_composite_venue", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_COMPOSITE_COURT.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_composite_court", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_COMPOSITE_PRODUCER.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_composite_producer", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_COMPOSITE_TRANSPORT.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_composite_transport", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_COMPOSITE_TRADE.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_composite_trade", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_COMPOSITE_MATING.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_composite_mating", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_PAY.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_pay", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_EXHIBITOR_SELF.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_exhibitor_self", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_CATERINGAPP.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_cateringapp", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_CATERING.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_catering", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_PORTAL_OUT_VENUE.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_portal_out_venue", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_PORTAL_OUT_OPERATION.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_portal_out_operation", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_PORTAL_IN_WORK.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_portal_in_work", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_PORTAL_IN_WORKAPP.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_portal_in_workapp", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_OPERATION_CENTER.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_operation_center", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_VISITOR_FRONT.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_visitor_front", BusinessConstant.YES)
                .eq(OrganizationOrgTypeEnum.P_VISITOR_BACK.getCode().equals(ContextUtil.getSystemScene()), "u.is_p_visitor_back", BusinessConstant.YES)

                //查询团队用户
                .eq(OrganizationOrgTypeEnum.P_COMPOSITE_PRODUCER.getCode().equals(ContextUtil.getSystemScene()) && ContextUtil.getTeamId() != null, "u.producer_id", ContextUtil.getTeamId())
                .eq(OrganizationOrgTypeEnum.P_COMPOSITE_COURT.getCode().equals(ContextUtil.getSystemScene()) && ContextUtil.getTeamId() != null, "u.court_id", ContextUtil.getTeamId())
                .eq(OrganizationOrgTypeEnum.P_COMPOSITE_TRANSPORT.getCode().equals(ContextUtil.getSystemScene()) && ContextUtil.getTeamId() != null, "u.transport_id", ContextUtil.getTeamId())
                .eq(OrganizationOrgTypeEnum.P_COMPOSITE_MATING.getCode().equals(ContextUtil.getSystemScene()) && ContextUtil.getTeamId() != null, "u.mating_id", ContextUtil.getTeamId())
        ;

    }

    public List<UserAccountVo> assembleUserDataVo(List<UserAccountVo> userAccountVoList) {
        if (userAccountVoList == null || userAccountVoList.isEmpty()) {
            return userAccountVoList;
        }
        for (UserAccountVo userAccountVo : userAccountVoList) {
            List<String> systemSceneList = new ArrayList<>();
            if (BusinessConstant.YES == userAccountVo.getIsPVenue()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_VENUE.getDesc());
            }
            if (BusinessConstant.YES == userAccountVo.getIsPCertificate()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_CERTIFICATE.getDesc());
            }
            if (BusinessConstant.YES == userAccountVo.getIsPCompositeVenue()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_COMPOSITE_VENUE.getDesc());
            }
            if (BusinessConstant.YES == userAccountVo.getIsPCompositeCourt()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_COMPOSITE_COURT.getDesc());
            }
            if (BusinessConstant.YES == userAccountVo.getIsPCompositeProducer()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_COMPOSITE_PRODUCER.getDesc());
            }
            if (BusinessConstant.YES == userAccountVo.getIsPCompositeTransport()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_COMPOSITE_TRANSPORT.getDesc());
            }
            if (BusinessConstant.YES == userAccountVo.getIsPCompositeTrade()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_COMPOSITE_TRADE.getDesc());
            }
            if (BusinessConstant.YES == userAccountVo.getIsPCompositeMating()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_COMPOSITE_MATING.getDesc());
            }
            if (BusinessConstant.YES == userAccountVo.getIsPPay()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_PAY.getDesc());
            }
            if (BusinessConstant.YES == userAccountVo.getIsPExhibitorSelf()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_EXHIBITOR_SELF.getDesc());
            }
            if (BusinessConstant.YES == userAccountVo.getIsPCateringapp()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_CATERINGAPP.getDesc());
            }
            if (BusinessConstant.YES == userAccountVo.getIsPCatering()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_CATERING.getDesc());
            }
            if (BusinessConstant.YES == userAccountVo.getIsPPortalOutVenue()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_PORTAL_OUT_VENUE.getDesc());
            }

            if (BusinessConstant.YES == userAccountVo.getIsPPortalOutOperation()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_PORTAL_OUT_OPERATION.getDesc());
            }
            if (BusinessConstant.YES == userAccountVo.getIsPPortalInWork()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_PORTAL_IN_WORK.getDesc());
            }
            if (BusinessConstant.YES == userAccountVo.getIsPPortalInWorkapp()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_PORTAL_IN_WORKAPP.getDesc());
            }
            if (BusinessConstant.YES == userAccountVo.getIsPOperationCenter()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_OPERATION_CENTER.getDesc());
            }
            if (BusinessConstant.YES == userAccountVo.getIsPVisitorFront()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_VISITOR_FRONT.getDesc());
            }
            if (BusinessConstant.YES == userAccountVo.getIsPVisitorBack()) {
                systemSceneList.add(OrganizationOrgTypeEnum.P_VISITOR_BACK.getDesc());
            }
            userAccountVo.setSystemSceneList(systemSceneList);
        }
        return userAccountVoList;
    }

    public void assemblePrivateKey(List<UserAccount> userAccountList) {
        for (UserAccount userAccount : userAccountList) {
            try {
                userAccount.setIdCard(TypeHandlerUtil.decrypt(userAccount.getIdCard()));
                userAccount.setMobile(TypeHandlerUtil.decrypt(userAccount.getMobile()));
//                userAccount.setPassword(RSAEncrypt.decrypt(userAccount.getPassword(), M9EncryptHandler.privateKey));
//                userAccount.setPassword(RSAEncrypt.decrypt(userAccount.getPassword(), M9EncryptHandler.privateKey));
                userAccount.setPassword(TypeHandlerUtil.decrypt(userAccount.getPassword()));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void assembleVoPrivateKey(List<UserAccountVo> userAccountVoList) {
        for (UserAccountVo userAccountVo : userAccountVoList) {
            try {
                userAccountVo.setIdCard(TypeHandlerUtil.decrypt(userAccountVo.getIdCard()));
                userAccountVo.setMobile(TypeHandlerUtil.decrypt(userAccountVo.getMobile()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public List<UserAccountVo> assembleUserOrg(List<UserAccountVo> userAccountVoList) {
        if (userAccountVoList == null || userAccountVoList.isEmpty()) {
            return userAccountVoList;
        }
        List<Long> userIds = userAccountVoList.stream().map(UserAccountVo::getId).collect(Collectors.toList());
        Map<Long, List<Organization>> map = organizationService.queryOrgOfUserId(userIds);
        if (map == null) {
            return userAccountVoList;
        }
        //组装组长信息
        List<UserOrganization> userOrganizationList = userOrganizationService.listOfUserOrganization(null, userIds, null);
        if (CollectionUtil.isNotEmpty(userOrganizationList)) {
            List<UserOrganizationVo> userOrganizationVoList = userOrganizationService.doToVos(userOrganizationList);
            loadUsrAccountOfLeader(userOrganizationVoList, userAccountVoList);
        }
        for (UserAccountVo userAccountVo : userAccountVoList) {
            List<Organization> organizationList = map.get(userAccountVo.getId());
            if (organizationList != null && !organizationList.isEmpty()) {
                userAccountVo.setOrgNameList(organizationList.stream().map(Organization::getName).collect(Collectors.toList()));
                userAccountVo.setOrgIds(organizationList.stream().map(Organization::getId).collect(Collectors.toList()));
            }
        }
        return userAccountVoList;
    }

    @Override
    public R<Boolean> updPassword(UserUpdPassParam userUpdPassParam) {
        UserAccount queryUserAccount = new UserAccount();
        queryUserAccount.setId(userUpdPassParam.getId());
        //查询用户
        UserAccount resultUserAccount = getUser(queryUserAccount);
        if (resultUserAccount != null) {
            //密码是否正确
            if (isValidPassword(userUpdPassParam.getOldPassword(), resultUserAccount.getPassword())) {
                resultUserAccount.setPassword(userUpdPassParam.getNewPassword());
            } else {
                return R.fail("原密码错误");
            }
            resultUserAccount.setPwdOutTime(LocalDateTime.now().plusDays(90));
            //更新密码
            updateById(resultUserAccount);
        }
        return R.success(true);
    }

    @Override
    public R<Boolean> updPasswordOfCode(UserUpdPassParam userUpdPassParam) {
        UserAccount queryUserAccount = new UserAccount();
        queryUserAccount.setMobile(userUpdPassParam.getMobile());
        //查询用户
        UserAccount resultUserAccount = getUser(queryUserAccount);
        if (resultUserAccount != null) {
            resultUserAccount.setPassword(userUpdPassParam.getNewPassword());
            resultUserAccount.setPwdOutTime(LocalDateTime.now().plusDays(90));
            //更新密码
            updateById(resultUserAccount);
            return R.success(true);
        } else {
            return R.fail(AuthServiceExceptionCode.USER_NO_SYSTEM);
        }

    }

    @Override
    public R<Boolean> setPassword(UserUpdPassParam userUpdPassParam) {
        //查询用户
        UserAccount resultUserAccount = getByIdCache(userUpdPassParam.getId());
        if (resultUserAccount != null) {
            resultUserAccount.setPassword(userUpdPassParam.getNewPassword());
            resultUserAccount.setPwdOutTime(LocalDateTime.now().plusDays(90));
            //更新密码
            updateById(resultUserAccount);
        }
        return R.success(true);
    }

    @Override
    public R<Boolean> initPassword(Long userId) {
        UserAccount queryUserAccount = new UserAccount();
        queryUserAccount.setId(userId);
        //查询用户
        UserAccount resultUserAccount = getUser(queryUserAccount);
        if (resultUserAccount != null) {
            resultUserAccount.setPassword(BusinessConstant.initPassword);
            resultUserAccount.setPwdOutTime(LocalDateTime.now().plusDays(90));
            //更新初始化密码
            updateById(resultUserAccount);
        }
        return R.success(true);
    }

    @Override
    public R<UserAccountVo> initRole(UserAccountDto userAccountDto) {
        UserAccount userAccount = getByIdCache(userAccountDto.getId());
        if (userAccount != null) {
            if (userAccountDto.getIsVisitor() == BusinessConstant.YES) {
                userAccount.setIsVisitor(BusinessConstant.YES);
                userAccount.setIsTourist(BusinessConstant.NO);

                //查询项目下的观众组
//                Organization organization = organizationService.queryOrgOfType(ContextUtil.getProjectId(), OrganizationOrgTypeEnum.P_AUDIENCE_CLASSIFY, null);
//                if (organization != null) {
//                    //添加到观众组
//                    audienceOrganizationService.addUseridOfClassifyOrg(ContextUtil.getProjectId(), organization.getId(), Arrays.asList(userAccountDto.getId()));
//                }
            } else if (userAccountDto.getIsEmployee() == BusinessConstant.YES) {
                userAccount.setIsEmployee(BusinessConstant.YES);
                userAccount.setIsTourist(BusinessConstant.NO);
            }
            updateById(userAccount);
        }
        return null;
    }

    @Override
    public R<List<UserAccountVo>> findByIds(List<Long> userIds) {
        QueryWrapper<UserAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .in(UserAccount::getId, userIds)
                .eq(UserAccount::getStatus, UserAccountStatusEnum.NORMAL);
        List<UserAccount> userAccountList = list(queryWrapper);
        return R.success(doToVos(userAccountList));
    }

    @Override
    public R<UserAccountVo> findById(Long userId) {
        if (userId == null || userId == 0) {
            return R.fail("获取用户失败");
        }
        UserAccount userAccount = new UserAccount();
        userAccount.setId(userId);
        userAccount = getUser(userAccount);
        UserAccountVo userAccountVo = doToVo(userAccount);
        //加载业务事件
        loadBusiness(userAccountVo);
        //加载用户角色信息
        loadUserRole(userAccountVo);
        return R.success(userAccountVo);
    }


//    @Override
//    public List<UserAccount> findRoleOfUserId(Long userId) {
//        return null;
//    }


    @Override
    public List<UserAccount> listOfUserAccount(UserAccount userAccount, List<Long> ids) {
        //查询
        QueryWrapper<UserAccount> queryWrapper = new QueryWrapper<>();
        if (userAccount != null) {
            if (userAccount.getId() != null) {
                queryWrapper.lambda().eq(UserAccount::getId, userAccount.getId());
            }
            if (StringUtils.isNotBlank(userAccount.getEmail())) {
                queryWrapper.lambda().eq(UserAccount::getEmail, userAccount.getEmail());
            }
            if (StringUtils.isNotBlank(userAccount.getMobile())) {
                queryWrapper.lambda().eq(UserAccount::getMobile, TypeHandlerUtil.crypt(userAccount.getMobile()));
            }
            if (StringUtils.isNotBlank(userAccount.getName())) {
//                queryWrapper.lambda().eq(UserAccount::getName, userAccount.getName());
                queryWrapper.and(wrapper -> {
                    wrapper.lambda().eq(UserAccount::getName, userAccount.getName());
                    wrapper.or();
                    wrapper.lambda().eq(UserAccount::getMobile, TypeHandlerUtil.crypt(userAccount.getName()));
                });
            }
        }
        if (ids != null && !ids.isEmpty()) {
            queryWrapper.lambda().in(UserAccount::getId, ids);
        }
        queryWrapper.lambda().eq(UserAccount::getIsDeleted, BusinessConstant.DELETE_NO);
        List<UserAccount> userAccountList = list(queryWrapper);
        return userAccountList;
    }

    @Override
    public List<UserAccountVo> listOfUserAccountVo(UserAccount userAccount, List<Long> ids) {
        List<UserAccount> userAccountList = listOfUserAccount(userAccount, ids);
        if (userAccountList != null && !userAccountList.isEmpty()) {
            return assembleUserOrgRole(doToVos(userAccountList));
        }
        return null;
    }

    public List<UserAccountVo> assembleUserOrgRole(List<UserAccountVo> userAccountList) {
        List<Long> userIds = userAccountList.stream().map(UserAccountVo::getId).collect(Collectors.toList());
        Map<Long, List<RoleVo>> userRoleMap = new HashMap<>();
        Map<Long, List<Organization>> userOrgMap = new HashMap<>();
        //查询用户部门
        userOrgMap = organizationService.queryOrgOfUserId(userIds);
        if (userOrgMap != null) {
            Set<Long> allOrgIdSet = new HashSet<>();
            for (List<Organization> organizationList : userOrgMap.values()) {
                if (CollectionUtils.isNotEmpty(organizationList)) {
                    allOrgIdSet.addAll(organizationList.stream().map(Organization::getId).collect(Collectors.toList()));
                }
            }
            //查询组织角色
            userRoleMap = organizationService.loadRoleOfMap(new ArrayList(allOrgIdSet));
            if (userRoleMap == null) {
                userRoleMap = new HashMap<>();
            }
        }
        //查询用户角色
        Map<Long, List<RoleVo>> userRoleMap2 = userRoleService.findRoleMapOfUser(userIds);
        if (userRoleMap2 != null) {
            userRoleMap.putAll(userRoleMap2);
        }

        for (UserAccountVo userAccountVo : userAccountList) {
            if (userOrgMap != null) {
                List<Organization> organizationList = userOrgMap.get(userAccountVo.getId());
                if (organizationList != null && !organizationList.isEmpty()) {
                    userAccountVo.setOrgNameList(organizationList.stream().map(Organization::getName).collect(Collectors.toList()));
                    userAccountVo.setOrgIds(organizationList.stream().map(Organization::getId).collect(Collectors.toList()));
                    userAccountVo.setOrganizationList(organizationList);
                }
            }
            List<RoleVo> roleVoList = userRoleMap.get(userAccountVo.getId());
            if (roleVoList != null && !roleVoList.isEmpty()) {
                userAccountVo.setRoleIds(roleVoList.stream().map(RoleVo::getId).collect(Collectors.toList()));
                userAccountVo.setRoleVoList(roleVoList);
                userAccountVo.setRoleNameList(roleVoList.stream().map(RoleVo::getName).collect(Collectors.toList()));
            }
        }
        return userAccountList;
    }

    @Override
    public UserAccountVo findOrgRoleOfUserId(Long userId) {
        UserAccount queryUserAccount = new UserAccount();
        queryUserAccount.setId(userId);
        queryUserAccount.setStatus(UserAccountStatusEnum.NORMAL);
        UserAccount resultUserAccount = getUser(queryUserAccount);
        if (resultUserAccount != null) {
            UserAccountVo userAccountVo = doToVo(resultUserAccount);
            //加载用户角色信息
            loadUserRole(userAccountVo);
            return userAccountVo;
        }
        return null;
    }

    @Override
    public R verifyMenu(Long userId, List<Long> menuIds) {
        //查询用户所拥有的菜单信息
        UserOrganization userOrganization = new UserOrganization();
        userOrganization.setUserId(userId);
        List<UserOrganization> userOrganizationList = userOrganizationService.listOfUserOrganization(userOrganization, null, null);
        if (userOrganizationList != null && !userOrganizationList.isEmpty()) {
            //查询组织信息
            List<Long> orgIds = userOrganizationList.stream().map(UserOrganization::getOrganizationId).collect(Collectors.toList());
            List<RoleVo> roleVoList = organizationService.loadRole(orgIds);
            //查询角色菜单关联信息
            List<MenuRole> menuRoleList = organizationService.loadMenuRole(roleVoList);
            //校验菜单是否超出范围
            if (menuRoleList != null && !menuRoleList.isEmpty()) {
                List<Long> userMenuIds = menuRoleList.stream().map(MenuRole::getMenuId).collect(Collectors.toList());
                for (Long menuId : menuIds) {
                    if (!userMenuIds.contains(menuId)) {
                        //菜单超出范围
                        return R.fail(MEUN_MORE);
                    }
                }
                return R.success();
            }
        }
        //菜单超出范围
        return R.fail(MEUN_MORE);
    }

    @Override
    public R removeByIds(List<Long> ids) {
        List<UserAccount> userAccountList = listByIds(ids);
        if (userAccountList != null && !userAccountList.isEmpty()) {
            for (UserAccount userAccount : userAccountList) {
                //1大后台操作，则删除用户，2业务系统操作，只账户解绑该系统
                if (OrganizationOrgTypeEnum.P.getCode().equals(ContextUtil.getSystemScene())) {
                    //真删
                    userAccount.setIsDeleted(BusinessConstant.DELETE_YES);
                } else {
                    //解绑
                    assembleSubSystem(userAccount, BusinessConstant.NO);
                }
                updateById(userAccount);
            }
        }
        return R.success();
    }


    @Override
    public R<Boolean> updateById(UserAccountDto userAccountDto) {
        UserAccount userAccount = getByIdCache(userAccountDto.getId());
        if (userAccount == null) {
            return R.fail("修改失败");
        }
//        if (StringUtils.isNotBlank(userAccountDto.getEmail())) {
//            userAccount.setEmail(userAccountDto.getEmail());
//        }
//        if (StringUtils.isNotBlank(userAccountDto.getName())) {
//            userAccount.setName(userAccountDto.getName());
//        }
//        if (StringUtils.isNotBlank(userAccountDto.getMobile())) {
//            userAccount.setMobile(userAccountDto.getMobile());
//        }
//
//        if (StringUtils.isNotBlank(userAccountDto.getIdCard())) {
//            userAccount.setIdCard(userAccountDto.getIdCard());
//        }
//        if (StringUtils.isNotBlank(userAccountDto.getRealName())) {
//            userAccount.setRealName(userAccountDto.getRealName());
//        }
//
//
//        userAccount.setHeadImg(userAccountDto.getHeadImg());
//        userAccount.setNickName(userAccountDto.getNickName());
        BeanUtils.copyProperties(userAccountDto, userAccount);
        //清除登录失败次数的redis缓存
        loginHandler.executeLoginSucc(userAccount.getId());
        return R.success(updateById(userAccount));
    }

    @Override
    public R<UserAccountVo> addAdminUser(UserAccountDto userAccountDto) {
        if (ContextUtil.getProjectId() == null) {
            //项目id不能为空
            return R.fail(PROJECT_ID_ERROR);
        }
        if (StringUtils.isBlank(userAccountDto.getName())) {
            //随机取name
            userAccountDto.setName(randomName(userAccountDto));
        }
        //查询用户是否存在，存在则更新
        QueryWrapper<UserAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserAccount::getIsDeleted, BusinessConstant.DELETE_NO);
        if (userAccountDto != null && (StringUtils.isNotBlank(userAccountDto.getEmail()) || StringUtils.isNotBlank(userAccountDto.getMobile()))) {
            queryWrapper.and(wrapper -> {
                if (StringUtils.isNotBlank(userAccountDto.getEmail())) {
                    wrapper.eq("email", userAccountDto.getEmail());
                    wrapper.or();
                }
                if (StringUtils.isNotBlank(userAccountDto.getMobile())) {
                    wrapper.eq("mobile", TypeHandlerUtil.crypt(userAccountDto.getMobile()));
                }
            });
        }
        //查询用户
        List<UserAccount> userAccountList = list(queryWrapper);
        if (userAccountList != null && !userAccountList.isEmpty()) {
            UserAccount userAccount = userAccountList.get(0);
            //修改
            userAccount.setName(userAccountDto.getName());
            userAccount.setMobile(userAccountDto.getMobile());
            userAccount.setEmail(userAccountDto.getEmail());
            updateById(userAccount);
            return R.success(doToVo(userAccount));
        } else {
            UserAccount saveUserAccount = BeanUtil.toBean(userAccountDto, getEntityClass());
            saveUserAccount.setStatus(UserAccountStatusEnum.NORMAL);
            saveUserAccount.setPassword(BusinessConstant.initPassword);
            save(saveUserAccount);
            return R.success(doToVo(saveUserAccount));
        }

    }

    public String randomName(UserAccountDto userAccountDto) {
        String name = "admin" + (new Random().nextInt(100000) + 100000);
        //查询用户是否存在
        QueryWrapper<UserAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserAccount::getName, name);
        queryWrapper.lambda().eq(UserAccount::getIsDeleted, BusinessConstant.DELETE_NO);
        //查询用户
        int i = count(queryWrapper);
        if (i > 0) {
            return randomName(userAccountDto);
        }
        return name;
    }

    @Override
    public UserAccountVo doToVo(UserAccount userAccount) {
        if(userAccount ==null){
            return null;
        }
        UserAccountVo userAccountVo = new UserAccountVo();
        BeanUtils.copyProperties(userAccount, userAccountVo);
        userAccountVo.setId(userAccount.getId());
        userAccountVo.setIsSetPassword(StringUtils.isNotBlank(userAccount.getPassword()) ? BusinessConstant.YES : BusinessConstant.NO);
        return userAccountVo;
    }

    @Override
    public List<UserAccountVo> doToVos(List<UserAccount> userAccountList) {
        if (userAccountList == null || userAccountList.isEmpty()) {
            return null;
        }
        List<UserAccountVo> result = new ArrayList<>();
        for (UserAccount userAccount : userAccountList) {
            result.add(doToVo(userAccount));
        }
        return result;
    }

    @Override
    public OrganizationVo findAllUserOfOrg(Organization organization) {
        if (organization == null) {
            return null;
        }
        OrganizationDTO organizationDTO = new OrganizationDTO();
        organizationDTO.setCode(organization.getCode());
        List<Organization> childOrganizationList = organizationService.queryAllOfCode(organizationDTO);
        List<OrganizationVo> organizationVoList = organizationService.doToVos(childOrganizationList);
        if (organizationVoList == null || organizationVoList.isEmpty()) {
            organizationVoList = new ArrayList<>();
        }
        organizationVoList.add(organizationService.doToVo(organization));
        //将用户和资源加载进去
        List<Long> orgIds = organizationVoList.stream().map(OrganizationVo::getId).collect(Collectors.toList());
        //批量查询节点的资源和用户信息
        List<UserOrganizationVo> userOrganizationVoList = userOrganizationService.queryUserVoByOrg(orgIds);
        if (userOrganizationVoList != null && !userOrganizationVoList.isEmpty()) {
            List<Long> userIds = userOrganizationVoList.stream().map(UserOrganizationVo::getUserId).collect(Collectors.toList());
            //查询userAccount
            List<UserAccountVo> userAccountVoList = doToVos(listOfUserAccount(null, userIds));
            //将用户和资源加载进去
            for (OrganizationVo organizationVo : organizationVoList) {
                //定义list
                List<UserOrganizationVo> userOrganizationVoList1 = new ArrayList<>();
                if (userOrganizationVoList != null && !userOrganizationVoList.isEmpty()) {
                    for (UserOrganizationVo userOrganizationVo : userOrganizationVoList) {
                        if (organizationVo.getId().equals(userOrganizationVo.getOrganizationId())) {
                            userOrganizationVoList1.add(userOrganizationVo);
                        }
                    }
                }
                if (userOrganizationVoList1 != null && !userOrganizationVoList1.isEmpty()) {
                    List<Long> userIdList = userOrganizationVoList1.stream().map(UserOrganizationVo::getUserId).collect(Collectors.toList());
                    organizationVo.setUserOrganizationVoList(userOrganizationVoList1);
                    List<UserAccountVo> userAccountVoList2 = userAccountVoList.stream().filter(s -> userIdList.contains(s.getId())).collect(Collectors.toList());
                    //组装负责人
                    loadUsrAccountOfLeader(userOrganizationVoList1, userAccountVoList2);
                    organizationVo.setUserAccountVoList(userAccountVoList2);
                }
            }
        }
        //整合组织
        return organizationService.loadTree(organization.getCode(), organizationVoList);
    }

    @Override
    public List<UserAccountVo> findAllLeaderUserOfOrg(Organization organization) {
        if (organization == null) {
            return null;
        }
        OrganizationVo organizationVo = organizationService.doToVo(organization);
        //批量查询节点的资源和用户信息
        List<UserOrganizationVo> userOrganizationVoList = userOrganizationService.queryUserVoByOrg(Arrays.asList(organizationVo.getId()));
        if (userOrganizationVoList != null && !userOrganizationVoList.isEmpty()) {
            //负责人信息
            List<Long> leaderUserIds = userOrganizationVoList.stream()
                    .filter(s -> s.getIsLeader() != null && s.getIsLeader() == BusinessConstant.YES)
                    .map(UserOrganizationVo::getUserId).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(leaderUserIds)) {
                return doToVos(listOfUserAccount(null, leaderUserIds));
            }
        }
        return null;
    }


    public void loadUsrAccountOfLeader(List<UserOrganizationVo> userOrganizationVoList, List<UserAccountVo> userAccountVoList) {
        //负责人信息
        List<Long> leaderUserIds = userOrganizationVoList.stream()
                .filter(s -> s.getIsLeader() != null && s.getIsLeader() == BusinessConstant.YES)
                .map(UserOrganizationVo::getUserId).collect(Collectors.toList());
        //组装负责人
        if (CollectionUtil.isNotEmpty(userAccountVoList)) {
            for (UserAccountVo userAccountVo : userAccountVoList) {
                userAccountVo.setIsLeader(BusinessConstant.NO);
            }
        }
        if (CollectionUtil.isNotEmpty(leaderUserIds) && CollectionUtil.isNotEmpty(userAccountVoList)) {
            for (UserAccountVo userAccountVo : userAccountVoList) {
                if (leaderUserIds.contains(userAccountVo.getId())) {
                    userAccountVo.setIsLeader(BusinessConstant.YES);
                }
            }
        }
    }

    /**
     * 校验项目是否是管理员项目
     *
     * @param projectId
     * @return
     */
    @Override
    public boolean verifyProjectIsAdmin(Long projectId) {
        //项目为管理员项目，则不用校验
        R<ProjectDb> r = projectCoreServiceFeign.getProjectById(projectId);
        if (r != null && SUCCESS_CODE == r.getCode() && r.getData() != null && r.getData().getIsAdmin() != null && r.getData().getIsAdmin() == BusinessConstant.YES) {
            return true;
        }
        return false;
    }
}
